<?php
 
if ( !defined( 'MEDIAWIKI' ) ) {
	die( 'This file is a MediaWiki extension, it is not a valid entry point' );
}
 
$wgExtensionFunctions[] = 'wfSetupPhpMorphy';
 
$wgExtensionCredits['parserhook'][] = array(
		'name' => 'PhpMorphy',
		'version' => '1.0',
		'description' => 'morphology word forms of Russian language',
);
 
$wgHooks['LanguageGetMagic'][]       = 'wfPhpMorphyLanguageGetMagic';
 
class ExtPhpMorphy {
	var $mPhpMorphy = null;
 
	function intgetform($word,$type,$args) {
		try {
			$base_form = $this->mPhpMorphy->castFormByGramInfo(mb_strtoupper($word), $type, $args, true);

			if ($base_form) {
				if (count($base_form) > 0) {
					return mb_strtolower($base_form[0]);
				}
			}
		} catch(phpMorphy_Exception $e) {}

		return $word;
	}
	
	function initialform( &$parser, $word = '') {
		return $this->intgetform($word,'КР_ПРИЛ', array('ЕД', 'СР'));
	}
 
	function encode( &$parser, $word = '') {
		return urlencode($word);
	}
 
	function getform( &$parser, $word = '', $number = 'ЕД', $form = 'РД') {
		return $this->intgetform($word,null,array($number,$form));
	}

	static function proceedTextual( $numeric ) {
		$numeric = (int) abs($numeric);
		$one = array("ЕД","ИМ");
		$two = array("ЕД","РД");
		$many = array("МН","РД");
		if ( $numeric % 100 == 1 || ($numeric % 100 > 20) && ( $numeric % 10 == 1 ) ) return $one;
		if ( $numeric % 100 == 2 || ($numeric % 100 > 20) && ( $numeric % 10 == 2 ) ) return $two;
		if ( $numeric % 100 == 3 || ($numeric % 100 > 20) && ( $numeric % 10 == 3 ) ) return $two;
		if ( $numeric % 100 == 4 || ($numeric % 100 > 20) && ( $numeric % 10 == 4 ) ) return $two;

		return $many;
		}
		
	function numberform( &$parser, $word = '', $number = 1) {
		return $this->intgetform($word,null,$this->proceedTextual($number));
	}

	function compile_media_type( &$parser, $theme, $theme2, $media = "") {
		$rod="";
		if (mb_strlen($media)==0){
			$media=$theme2;
			$theme2="";
		}

		switch ($media){
			case "Газета":
				$rod="ЖР";
				break;
			case "Журнал":
				$rod="МР";
				break;
			case "Радиостанция":
				$rod="ЖР";
				break;
			case "Телеканал":
				$rod="МР";
				break;
			case "Агенство":
				$rod="СР";
				break;
		}
		$media = $this->intgetform($media,null, array("ЕД", "ИМ"));
		$result="";
		if (mb_strlen($theme2)==0){
            switch ($theme) {
                case 'Общественно-политические':
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Экономические и бухгалтерские':
                    $result = $this->intgetform("Экономические","П", array("ЕД", "ИМ", $rod))." и ".
                        $this->intgetform("Бухгалтерские","П", array("ЕД", "ИМ", $rod)).
                        " $media";
                    break;
                case 'Рекламно-информационные':
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Информационно-аналитические': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Правовые': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Развлекательные':
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Детские': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Молодежные': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Для женщин': 
                    $result = "$media ".mb_strtolower($theme);
                    break;
                case 'Для мужчин': 
                    $result = "$media ".mb_strtolower($theme);
                    break;
                case 'Автомобильные': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Хобби': 
                    $result = "$media о хобби";
                    break;
                case 'Научно-популярные и образовательные':
                    $result = $this->intgetform("Научно-популярные","П", array("ЕД", "ИМ", $rod))." и "
                    .$this->intgetform("образовательные","П", array("ЕД", "ИМ", $rod)).
                    " $media";
                    break;
                case 'Криминальная хроника, детективы': 
                    $result = "$media-криминальная хроника, детектив";
                    break;
                case 'Спортивные': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Отдых и туризм':
                    $result = "$media об отдыхе и туризме";
                    break;
                case 'Медицина и фармакология':
                    $result = "$media о медицине и фармакологии";
                    break;
                case 'Экология':
                    $result = "$media об экологии";
                    break;
                case 'Для дачников и огородников':
                    $result = "$media для дачников и огородников";
                    break;
                case 'Проблемы с/х и крестьянства':
                    $result = "$media о проблемах с\\х и крестьянства";
                    break;
                case 'Религиозные': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Издания национальностей':
                    $result = "$media-издание национальностей";
                    break;
                case 'Защиты интересов трудящихся':
                    $result = "$media о защите интересов трудящихся";
                    break;
                case 'Партийные': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Литературно-искусствоведческие': 
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
                case 'Проблемы любви':
                    $result = "$media о проблемах любви";
                    break;
                case 'Трудоустройство, обучение, услуги':
                    $result = "$media о трудоустройстве, обучении, услугах";
                    break;
                case 'Наукоемкие технологии, компьютеры':
                    $result = "$media о наукоёмких технологиях, компьютерах";
                    break;
                case 'Специализированные':
                    $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." $media";
                    break;
            }
		} else {
            $result = $this->intgetform($theme,"П", array("ЕД", "ИМ", $rod))." ".$this->intgetform($theme2,"П", array("ЕД", "ИМ", $rod))." $media";
        }
		
		if (strlen($result)>0) {
			$result = mb_strtoupper(mb_substr($result,0,1)).mb_strtolower(mb_substr($result,1));
		}
		return $result;
	}

	function getformlive( &$parser, $expr = '', $value = '' ) {
		return $expr."vvv";
	}
}
 
function wfSetupPhpMorphy() {
	global $wgParser, $wgExtPhpMorphy, $wgHooks;
 
	// first we include phpmorphy library
	require_once(dirname(__FILE__) . '/src/common.php');

	$opts = array(
		// storage type, follow types supported
		// PHPMORPHY_STORAGE_FILE - use file operations(fread, fseek) for dictionary access, this is very slow...
		// PHPMORPHY_STORAGE_SHM - load dictionary in shared memory(using shmop php extension), this is preferred mode
		// PHPMORPHY_STORAGE_MEM - load dict to memory each time when phpMorphy intialized, this useful when shmop ext. not activated. Speed same as for PHPMORPHY_STORAGE_SHM type
		'storage' => PHPMORPHY_STORAGE_SHM,
		// Extend graminfo for getAllFormsWithGramInfo method call
		'with_gramtab' => false,
		// Enable prediction by suffix
		'predict_by_suffix' => true, 
		// Enable prediction by prefix
		'predict_by_db' => true
	);

	// Path to directory where dictionaries located
	$dir = dirname(__FILE__) . '/dicts';
	// Create descriptor for dictionary located in $dir directory with russian language
	$dict_bundle = new phpMorphy_FilesBundle($dir, 'rus');

	// Create phpMorphy instance
	try {
		$morphy = new phpMorphy($dict_bundle, $opts);
	} catch(phpMorphy_Exception $e) {
		die('Error occured while creating phpMorphy instance: ' . $e->getMessage());
	}
	
	$wgExtPhpMorphy = new ExtPhpMorphy;
	$wgExtPhpMorphy->mPhpMorphy = $morphy;
 
	$wgParser->setFunctionHook( 'encode', array( &$wgExtPhpMorphy, 'encode' ) );
	$wgParser->setFunctionHook( 'initialform', array( &$wgExtPhpMorphy, 'initialform' ) );
	$wgParser->setFunctionHook( 'getform', array( &$wgExtPhpMorphy, 'getform' ) );
	$wgParser->setFunctionHook( 'compile_media_type', array( &$wgExtPhpMorphy, 'compile_media_type' ) );
	$wgParser->setFunctionHook( 'numberform', array( &$wgExtPhpMorphy, 'numberform' ) );
}
 
function wfPhpMorphyLanguageGetMagic( &$magicWords, $langCode = 0 ) {
		require_once( dirname( __FILE__ ) . '/PhpMorphy.i18n.php' );
		foreach( efPhpMorphyWords( $langCode ) as $word => $trans )
			$magicWords[$word] = $trans;
		return true;
}
